package com.geekerp.authorization_server.sms2;


import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.Map;

public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String PHONE_KEY = "phone";  // 手机号字段
    public static final String CAPTCHA_KEY = "captcha";  // 验证码字段

    private boolean postOnly = true;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public SmsAuthenticationFilter() {
        super("/login/sms"); // 拦截短信验证码登录请求
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String phone;
        String captcha;

        try {
            // 读取请求体中的 JSON 数据并解析
            Map<String, String> requestBody = objectMapper.readValue(request.getInputStream(), Map.class);
            phone = requestBody.get(PHONE_KEY);  // 获取手机号
            captcha = requestBody.get(CAPTCHA_KEY);  // 获取验证码
        } catch (IOException e) {
            throw new AuthenticationServiceException("Failed to parse authentication request body", e);
        }

        if (phone == null) {
            phone = "";
        }

        if (captcha == null) {
            captcha = "";
        }

        phone = phone.trim();

        // 创建验证请求的 Token
        SmsAuthenticationToken authRequest = new SmsAuthenticationToken(phone, captcha);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
}